package com.spring.sunflower.main.fragment;

import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.makeramen.roundedimageview.RoundedImageView;
import com.spring.sunflower.R;
import com.spring.sunflower.anchor.PersonalDetailActivity;
import com.spring.sunflower.base.BaseFragment;
import com.spring.sunflower.bean.RecommendAnchorsBean;
import com.spring.sunflower.bean.LabelBean;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.main.MainContract;
import com.spring.sunflower.main.adapter.RecommendLabelAdapter;
import com.spring.sunflower.main.presenter.RecommendPresenter;
import com.spring.sunflower.util.DisplayUtils;
import com.spring.sunflower.util.AppUtils;
import com.spring.sunflower.widget.ObservableScrollView;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Kevin on 2021/6/16<br/>
 * <p>
 * Describe:<br/>
 */
public class RecommendFragment extends BaseFragment<RecommendPresenter> implements MainContract.RecommendView {
    private RecyclerView mRecyclerViewLabel;
    private RecommendLabelAdapter recommendLabelAdapter;
    private List<LabelBean.DatasBean> labelData = new ArrayList<>();
    private List<RecommendAnchorsBean.DatasBean> anchorData = new ArrayList<>();
    private List<View> showViews = new ArrayList<>();
    private RelativeLayout contentLayout;
    private int contentLayoutHeight;
    private ObservableScrollView scrollView;
    private int count = 0;
    private List<String> mSelectLabel = new ArrayList<>();
    private RecommendAnchorsBean.DatasBean datasBean;
    private int clickPos = 0;
    private List<Animation> mAnimData = new ArrayList<>();

    @Override
    public int setLayoutResId() {
        return R.layout.fragment_recommend;
    }

    @Override
    public void initView() {
        scrollView = mView.findViewById(R.id.scroll_view);
        contentLayout = (RelativeLayout) mView.findViewById(R.id.content_layout);
        mRecyclerViewLabel = mView.findViewById(R.id.rvRecyclerViewLabel);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false);
//        GridLayoutManager gridLayoutManager = new GridLayoutManager(mActivity, 4);
        mRecyclerViewLabel.setLayoutManager(layoutManager);
//        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mActivity, LinearLayoutManager.HORIZONTAL);
//        dividerItemDecoration.setDivider(R.drawable.divider_horizontal);
//        mRecyclerViewLabel.addItemDecoration(dividerItemDecoration);
        recommendLabelAdapter = new RecommendLabelAdapter(R.layout.adapter_recommend_label, labelData);
        mRecyclerViewLabel.setAdapter(recommendLabelAdapter);
        contentLayoutHeight = AppUtils.getDisplayHeight(getActivity()) -
                DisplayUtils.dip2px(getActivity(), 204);

    }

    @Override
    public void initData() {
        mPresenter.getVisualizeLabel();
//        mPresenter.getRecommendAnchors(1);
    }

    @Override
    public void initListener() {
        addOnScrollChangeListener();
        recommendLabelAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
//                if (isFastClick()) {
//
//                }
                LabelBean.DatasBean datasBean = labelData.get(position);
                String name = datasBean.getName();
                String id = datasBean.getId();
                int index = mSelectLabel.indexOf(id);
                if (datasBean.isChecked()) {
                    if (position == clickPos) return;
                    datasBean.setChecked(false);
                    if (index != -1) {
                        mSelectLabel.remove(index);
                    }
                } else {
                    datasBean.setChecked(true);
                    if (mSelectLabel.size() > 0) {
                        String str = mSelectLabel.get(0);
                        for (LabelBean.DatasBean b : labelData) {
                            if (b.getId().equals(str)) {
                                b.setChecked(false);
                            }
                        }
                        mSelectLabel.clear();
                    }
                    mSelectLabel.add(id);
                }
                clickPos = position;
                mPresenter.getRecommendAnchors(1, id);
                recommendLabelAdapter.notifyDataSetChanged();
                scrollView.scrollTo(0, 0);
//                datasBean.
//                TextView tv = (TextView) adapter.getViewByPosition(position, R.id.tvLabel);
//                tv.setTextColor(ContextCompat.getColor(mActivity, R.color.white));
//                for (int i = 0; i < labelData.size(); i++) {
//                    RecommendBean.DatasBean datasBean1 = labelData.get(position);
//                    if (i == position) {
//                        datasBean1.setChecked(true);
//                    } else {
//                        datasBean1.setChecked(false);
//                    }
//                    recommendLabelAdapter.setData(position, datasBean1);
//                }
            }
        });
        initClickListener();
    }

    @Override
    public void loadData() {

    }

    @Override
    public RecommendPresenter setPresenter() {
        return new RecommendPresenter(this);
    }

    @Override
    public void showLabelData(List<LabelBean.DatasBean> data) {
        Random random = new Random();
        List<LabelBean.DatasBean> list = new ArrayList<>();
        while (list.size() < 5) {
            int i = random.nextInt(data.size());
            if (!list.contains(data.get(i))) {
                list.add(data.get(i));
            }
        }
        if (list.size() > 0) {
            LabelBean.DatasBean datasBean = list.get(0);
            datasBean.setChecked(true);
            mSelectLabel.add(datasBean.getId());
            mPresenter.getRecommendAnchors(1, datasBean.getId());
        }
        recommendLabelAdapter.setList(list);
    }

    @Override
    public void showAnchorData(List<RecommendAnchorsBean.DatasBean> data) {
        stopRotateAnim();
        mAnimData.clear();
        anchorData.clear();
        anchorData.addAll(data);
        int id = R.id.recommend_anchor_img_01;
        int flID = R.id.fl_01;
        int animId = R.id.img_01;
        int childCount = contentLayout.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = contentLayout.getChildAt(i);
            child.setVisibility(View.GONE);
        }
//        printI("animId1=" + R.id.img_01 + "," + R.id.fl_01);
//        printI("animId2=" + R.id.img_02 + "," + R.id.fl_02);
//        printI("animId3=" + R.id.img_03 + "," + R.id.fl_03);
//        printI("animId4=" + R.id.img_04 + "," + R.id.fl_04);
        for (int i = 0; i < data.size() && i < childCount; i++, id++, flID++, animId++) {
//            printW("flID=" + id);
//            printD("flID=" + flID);
//            printI("animId=" + animId);

            RelativeLayout flContent = mView.findViewById(flID);
            ImageView ivAnim = mView.findViewById(animId);
            RoundedImageView imageView = mView.findViewById(id);
            flContent.setVisibility(View.INVISIBLE);
//            showViews.add(flContent);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startRotateAnim(ivAnim);
                }
            }, 1000);
            printD("i==" + i);
            datasBean = data.get(i);
            if (datasBean.getStatus().equals("4")) {
                ivAnim.setVisibility(View.VISIBLE);
            } else {
                ivAnim.setVisibility(View.GONE);
            }
            Glide.with(mActivity)
                    .load((datasBean.getCoverUrl() == null || datasBean.getCoverUrl() == "") ? datasBean.getPhoto() : datasBean.getCoverUrl())
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                    .placeholder(R.drawable.ic_placeholder)
                    .error(R.drawable.ic_placeholder)
                    .into(imageView);
//                GlideUtils.loadCircleAvatar(getActivity(), anchorList.get(i).getUserIcon(), imageView);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) flContent.getLayoutParams();
            if (layoutParams.topMargin < contentLayoutHeight && !flContent.isShown()) {
                printD("Hello=" + i);
                startAnimation(flContent);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        startRotateAnim();
        printD("onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                stopRotateAnim();
            }
        }, 500);
        printD("onPause");
    }

    private void startAnimation(final View view) {
        view.setVisibility(View.VISIBLE);
        ScaleAnimation scale1 = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scale1.setDuration(1000);
        ScaleAnimation scale2 = new ScaleAnimation(1.4f, 1.0f, 1.4f, 1.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scale2.setDuration(400);
        scale2.setStartOffset(1000);
        AlphaAnimation alpha = new AlphaAnimation(0.0f, 1.0f);
        alpha.setDuration(1400);
        AnimationSet animationSet = new AnimationSet(true);
        animationSet.addAnimation(scale1);
        animationSet.addAnimation(scale2);
        animationSet.addAnimation(alpha);
        view.setAnimation(animationSet);
    }

    private void startRotateAnim(View view) {
        RotateAnimation animation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(3000);
        animation.setRepeatCount(-1);
        animation.setFillAfter(true);
        view.startAnimation(animation);
        mAnimData.add(animation);
    }

    private void startRotateAnim() {
        if (mAnimData.isEmpty()) return;
        for (int i = 0; i < mAnimData.size(); i++) {
            Animation animation = mAnimData.get(i);
            if (animation != null) {
                animation.start();
            }
        }
    }

    private void stopRotateAnim() {
        if (mAnimData.isEmpty()) return;
        for (int i = 0; i < mAnimData.size(); i++) {
            Animation animation = mAnimData.get(i);
            if (animation != null) {
                animation.cancel();
            }
        }
    }

    private void initClickListener() {
        for (int i = 0, id = R.id.fl_01; i < contentLayout.getChildCount(); i++, id++) {
            RelativeLayout frameLayout = mView.findViewById(id);
            frameLayout.setOnClickListener(onClickListener);
        }
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
//            stopRotateAnim();
            int id = v.getId();
            int position = id - R.id.fl_01;
//            showToast("index=" + (position));
//            showToast("position=" + position);
            RecommendAnchorsBean.DatasBean datasBean = anchorData.get(position);
            Intent intent = new Intent(getActivity(), PersonalDetailActivity.class);
            intent.putExtra(Constant.KEY_TARGET_ID, String.valueOf(datasBean.getMemberId()));
            startActivity(intent);
        }
    };

    private void addOnScrollChangeListener() {
        scrollView.setOnScrollListener(new ObservableScrollView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(ObservableScrollView view, int scrollState) {
                switch (scrollState) {
                    case SCROLL_STATE_IDLE:
//                        mActivity.startShowAnimation();
//                        handler.postDelayed(runnable, 200);
                        break;
                    case SCROLL_STATE_TOUCH_SCROLL:
                        break;
                    case SCROLL_STATE_FLING:
                        break;
                }
            }

            @Override
            public void onScroll(ObservableScrollView observableScrollView, boolean isTouchScroll, int x, int y, int oldx, int oldy) {

                int deltY = y - oldy;
//                mActivity.translateView(deltY);
                if (deltY > 0) {
                    int count = anchorData.size();
                    for (int i = 0; i < count && i < contentLayout.getChildCount(); i++) {
                        View view = contentLayout.getChildAt(i);
                        if (view != null) {
                            int top = view.getTop();
                            if (!view.isShown() && y > top - contentLayoutHeight) {
                                startAnimation(view);
                            }
                        }
                    }
//                    rvTab.setVisibility(View.GONE);
                }
            }
        });


    }
}
